using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Admin.NET.Application.LAKALA.Dto.Response;
using Admin.NET.Application.Service.LKL.Dto.KeTuo;
using Furion;
using Furion.FriendlyException;
using NewLife.Caching;
using Newtonsoft.Json;

namespace Admin.NET.Application.LAKALA;

public class LKLUtil
{
	private static string appId = "OP00003040";

	private static string orgCode = "1";

	private static string serialNo = "0191261e7fdf";

	private static string nonceStr = GetNonceStr(12);

	private static string timeStamp = DateTimeOffset.Now.ToUnixTimeSeconds().ToString();

	private static string client_id = "yuyao";

	private static string client_secret = "KnShArIz5zMbF76p";

	private static string user_name = "18913908768";

	private static string pwd = "yuyao@123";

	private static List<Attchments> imageInfos = new List<Attchments>
	{
		new Attchments
		{
			type = "CHECKSTAND_IMG",
			id = "merchant/null/20240828201930459782CHECKSTAND_IMG.jpg",
			SystemUrl = "https://aimeter.njsnh.com:15006/Upload/2024/08/28/36526686125829.jpg"
		},
		new Attchments
		{
			type = "CHECKSTAND_IMG",
			id = "merchant/null/20240828202016480870CHECKSTAND_IMG.jpg",
			SystemUrl = "https://aimeter.njsnh.com:15006/Upload/2024/08/28/36526698072581.jpg"
		},
		new Attchments
		{
			type = "CHECKSTAND_IMG",
			id = "merchant/null/20240828202044841896CHECKSTAND_IMG.jpg",
			SystemUrl = "https://aimeter.njsnh.com:15006/Upload/2024/08/28/36526705204741.jpg"
		},
		new Attchments
		{
			type = "CHECKSTAND_IMG",
			id = "merchant/null/20240828202108011809CHECKSTAND_IMG.jpg",
			SystemUrl = "https://aimeter.njsnh.com:15006/Upload/2024/08/28/36526711325957.jpg"
		},
		new Attchments
		{
			type = "CHECKSTAND_IMG",
			id = "merchant/null/20240828202138531912CHECKSTAND_IMG.jpg",
			SystemUrl = "https://aimeter.njsnh.com:15006/Upload/2024/08/28/36526719139333.jpg"
		},
		new Attchments
		{
			type = "CHECKSTAND_IMG",
			id = "merchant/null/20240828202210518472CHECKSTAND_IMG.jpg",
			SystemUrl = "https://aimeter.njsnh.com:15006/Upload/2024/08/28/36526727338245.jpg"
		},
		new Attchments
		{
			type = "SHOP_OUTSIDE_IMG",
			id = "merchant/null/20240828202401459616SHOP_OUTSIDE_IMG.jpg",
			SystemUrl = "https://aimeter.njsnh.com:15006/Upload/2024/08/28/36526755518725.jpg"
		},
		new Attchments
		{
			type = "SHOP_OUTSIDE_IMG",
			id = "merchant/null/20240828202431836389SHOP_OUTSIDE_IMG.jpg",
			SystemUrl = "https://aimeter.njsnh.com:15006/Upload/2024/08/28/36526762912773.jpg"
		},
		new Attchments
		{
			type = "SHOP_OUTSIDE_IMG",
			id = "merchant/null/20240828202455529028SHOP_OUTSIDE_IMG.jpeg",
			SystemUrl = "https://aimeter.njsnh.com:15006/Upload/2024/08/28/36526769597189.jpeg"
		},
		new Attchments
		{
			type = "SHOP_OUTSIDE_IMG",
			id = "merchant/null/20240828202528047523SHOP_OUTSIDE_IMG.jpg",
			SystemUrl = "https://aimeter.njsnh.com:15006/Upload/2024/08/28/36526777847045.jpg"
		},
		new Attchments
		{
			type = "SHOP_OUTSIDE_IMG",
			id = "merchant/null/20240828202553720178SHOP_OUTSIDE_IMG.jpeg",
			SystemUrl = "https://aimeter.njsnh.com:15006/Upload/2024/08/28/36526784400133.jpeg"
		},
		new Attchments
		{
			type = "SHOP_INSIDE_IMG",
			id = "merchant/null/20240828202639830001SHOP_INSIDE_IMG.jpeg",
			SystemUrl = "https://aimeter.njsnh.com:15006/Upload/2024/08/28/36526796030213.jpeg"
		},
		new Attchments
		{
			type = "SHOP_INSIDE_IMG",
			id = "merchant/null/20240828202703544321SHOP_INSIDE_IMG.jpeg",
			SystemUrl = "https://aimeter.njsnh.com:15006/Upload/2024/08/28/36526802333957.jpeg"
		},
		new Attchments
		{
			type = "SHOP_INSIDE_IMG",
			id = "merchant/null/20240828202728371416SHOP_INSIDE_IMG.jpeg",
			SystemUrl = "https://aimeter.njsnh.com:15006/Upload/2024/08/28/36526808544261.jpeg"
		},
		new Attchments
		{
			type = "SHOP_INSIDE_IMG",
			id = "merchant/null/20240828202752304954SHOP_INSIDE_IMG.jpg",
			SystemUrl = "https://aimeter.njsnh.com:15006/Upload/2024/08/28/36526814791941.jpg"
		},
		new Attchments
		{
			type = "SHOP_INSIDE_IMG",
			id = "merchant/null/20240828202814540612SHOP_INSIDE_IMG.jpeg",
			SystemUrl = "https://aimeter.njsnh.com:15006/Upload/2024/08/28/36526820355589.jpeg"
		},
		new Attchments
		{
			type = "SHOP_INSIDE_IMG",
			id = "merchant/null/20240828202837871911SHOP_INSIDE_IMG.jpeg",
			SystemUrl = "https://aimeter.njsnh.com:15006/Upload/2024/08/28/36526826296837.jpeg"
		},
		new Attchments
		{
			type = "BANK_CARD",
			id = "merchant/null/20240828203037747258BANK_CARD.jpeg",
			SystemUrl = "https://aimeter.njsnh.com:15006/Upload/2024/08/28/36526857073413.jpeg"
		},
		new Attchments
		{
			type = "BANK_CARD",
			id = "merchant/null/20240828203105296505BANK_CARD.jpeg",
			SystemUrl = "https://aimeter.njsnh.com:15006/Upload/2024/08/28/36526864279557.jpeg"
		},
		new Attchments
		{
			type = "BANK_CARD",
			id = "merchant/null/20240828203133642572BANK_CARD.jpg",
			SystemUrl = "https://aimeter.njsnh.com:15006/Upload/2024/08/28/36526871374341.jpg"
		}
	};

	public static Attchments GetPhoto(string type)
	{
		List<Attchments> model = imageInfos.Where((Attchments u) => u.type == type).ToList();
		Random r = new Random();
		int n = r.Next(0, model.Count - 1);
		return model[n];
	}

	/// <summary>
	/// 获得通用token
	/// </summary>
	/// <returns></returns>
	public static async Task<string> GetOrdinaryToken()
	{
		ICache cache = App.GetService<ICache>();
		string result = cache.Get<string>("OrdinaryToken");
		string url = "https://tkapi.lakala.com/auth/oauth/token?grant_type=client_credentials&client_id=" + client_id + "&client_secret=" + client_secret;
		using (HttpClient client = HttpClientFactory.Create())
		{
			TokenOrdinary token = JsonConvert.DeserializeObject<TokenOrdinary>(await (await client.PostAsync(url, null)).Content.ReadAsStringAsync());
			result = token.access_token;
			cache.Set("OrdinaryToken", result, 600);
		}
		return result;
	}

	/// <summary>
	/// 获得更改token
	/// </summary>
	/// <returns></returns>
	public static async Task<string> GetEditToken()
	{
		ICache cache = App.GetService<ICache>();
		string result = cache.Get<string>("OrdinaryEditToken");
		string url = "https://htkapi.lakala.com/auth/oauth/token";
		string boundary = DateTime.Now.Ticks.ToString("x");
		using (HttpClient client = HttpClientFactory.Create())
		{
			client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(client_id + ":" + client_secret)));
			MultipartFormDataContent content = new MultipartFormDataContent(boundary);
			content.Add(new ReadOnlyMemoryContent(Encoding.UTF8.GetBytes(user_name)), "\"username\"");
			content.Add(new ReadOnlyMemoryContent(Encoding.UTF8.GetBytes(pwd)), "\"password\"");
			content.Add(new ReadOnlyMemoryContent(Encoding.UTF8.GetBytes("password")), "\"grant_type\"");
			content.Add(new ReadOnlyMemoryContent(Encoding.UTF8.GetBytes("all")), "\"scope\"");
			content.Headers.Remove("Content-Type");
			content.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
			TokenOrdinary token = JsonConvert.DeserializeObject<TokenOrdinary>(await (await client.PostAsync(url, content)).Content.ReadAsStringAsync());
			result = token.access_token;
			cache.Set("OrdinaryEditToken", result, 600);
		}
		return result;
	}

	/// <summary>
	/// 初始化
	/// </summary>
	/// <param name="_appid"></param>
	/// <param name="_seriano"></param>
	/// <param name="_orgcode"></param>
	public static void Init(string _appid, string _seriano, string _orgcode)
	{
		appId = _appid;
		serialNo = _seriano;
		orgCode = _orgcode;
	}

	/// <summary>
	/// http调用
	/// </summary>
	/// <param name="url"></param>
	/// <param name="content"></param>
	/// <returns></returns>
	public static async Task<T> LKLClientRequest<T>(string url, string content)
	{
		using HttpClient client = HttpClientFactory.Create();
		StringContent stringContent = new StringContent(content);
		stringContent.Headers.Remove("Content-Type");
		stringContent.Headers.Add("Content-Type", "application/json");
		string auth = GetAuthorizationHeader(content);
		client.DefaultRequestHeaders.Add("Authorization", auth);
		return JsonConvert.DeserializeObject<T>(await (await client.PostAsync(url, stringContent)).Content.ReadAsStringAsync());
	}

	public static async Task<T> LKLClientPostKTRequest<T>(string url, string content, string token)
	{
		using HttpClient client = HttpClientFactory.Create();
		StringContent stringContent = new StringContent(content);
		stringContent.Headers.Remove("Content-Type");
		stringContent.Headers.Add("Content-Type", "application/json");
		client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
		HttpResponseMessage responseMessage = await client.PostAsync(url, stringContent);
		string resultValue = await responseMessage.Content.ReadAsStringAsync();
		if (responseMessage.StatusCode != HttpStatusCode.OK)
		{
			throw Oops.Bah(resultValue);
		}
		return JsonConvert.DeserializeObject<T>(resultValue);
	}

	public static async Task<T> LKLClientGetKTRequest<T>(string url, string token)
	{
		using HttpClient client = HttpClientFactory.Create();
		client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
		string resultValue = await (await client.GetAsync(url)).Content.ReadAsStringAsync();
		Console.WriteLine(resultValue + "----------------------------");
		return JsonConvert.DeserializeObject<T>(resultValue);
	}

	/// <summary>
	///
	/// </summary>
	/// <param name="lenth"></param>
	/// <returns></returns>
	public static string GetNonceStr(int lenth)
	{
		string result = "";
		Random rand = new Random();
		char[] strmap = "0123456789abcdefghijklmnopqrstuvwxyz".ToCharArray();
		for (int i = 0; i < lenth; i++)
		{
			result += strmap[rand.Next() % strmap.Length];
		}
		return result;
	}

	public static string Sign(byte[] data)
	{
		Console.WriteLine(AppDomain.CurrentDomain.BaseDirectory + "LAKALA/cer/lakala-laop-iis-0808100711.pfx");
		X509Certificate2 mycert = new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + "LAKALA/cer/lakala-laop-iis-0808100711.pfx");
		RSA pri = mycert.GetRSAPrivateKey();
		byte[] result = pri.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
		mycert.Dispose();
		return Convert.ToBase64String(result);
	}

	public static bool Verify(byte[] data, byte[] signature)
	{
		X509Certificate2 lklcert = new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + "LAKALA/cer/lkl-apigw-v1.cer");
		RSA pub = (RSA)lklcert.PublicKey.Key;
		bool bol = pub.VerifyData(data, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
		lklcert.Dispose();
		return bol;
	}

	public static string GetAuthorizationHeader(string strBody)
	{
		string reqbody = appId + "\n" + serialNo + "\n" + timeStamp + "\n" + nonceStr + "\n" + strBody + "\n";
		string signature = Sign(Encoding.UTF8.GetBytes(reqbody));
		return "LKLAPI-SHA256withRSA appid=\"" + appId + "\",serial_no=\"" + serialNo + "\",timestamp=\"" + timeStamp + "\",nonce_str=\"" + nonceStr + "\",signature=\"" + signature + "\"";
	}

	public static T GetResult<T, F>(T temp, F copy)
	{
		Type typeF = typeof(F);
		Type typeT = typeof(T);
		PropertyInfo[] properties = typeF.GetProperties();
		foreach (PropertyInfo item in properties)
		{
			object obj = item.GetValue(copy);
			PropertyInfo properT = (from u in typeT.GetProperties()
				where u.Name.ToLower() == item.Name.ToLower()
				select u).FirstOrDefault();
			if (properT != null && properT.CanWrite)
			{
				properT.SetValue(temp, obj);
			}
		}
		return temp;
	}
}
